#pragma once
#include<string>
#include<iostream>
#include<stdlib.h>
#include<memory>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
using namespace std;

class client
{
public:
    client(const string& serverip,const uint16_t serverport)
    :_serverip(serverip),_serverport(serverport),_sockfd(-1),_quit(false)
    {}

    void initClient()
    {
        //创建socket
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd==-1)
        {
            cerr<<"sockfd error: "<<errno<<" : "<<strerror(errno)<<endl;
            exit(2);
        }
        cout<<"socket success: "<<_sockfd<<endl;
    }

    //客户端不需要显示的bind
    void run()
    {
        struct sockaddr_in ser;
        memset(&ser,0,sizeof(ser));
        ser.sin_family = AF_INET;//绑定协议家族
        //将点分十进制的字符串转换成32位的IP地址
        ser.sin_addr.s_addr = inet_addr(_serverip.c_str());
        ser.sin_port = htons(_serverport);//主机转换成网络字节序

        string message;
        while(!_quit)
        {   
            cout<<"Please Enter# ";
            cin>>message;
            
            int n = sendto(_sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&ser,sizeof(ser));
            //cout<<n<<":"<<strerror(errno)<<endl;
        }
    }

    ~client(){}

private:
    int _sockfd;
    string _serverip;
    uint16_t _serverport;
    bool _quit;
};